package com.knife.blog.service;

import com.knife.util.CommUtil;
import com.knife.util.HtmlUtil;
import com.knife.web.RequestProcessor;
import com.knife.web.tools.CommTool;
import com.knife.web.tools.IPageList;
import com.knife.blog.domain.BlogInfo;
import com.knife.blog.domain.BlogNewsDoc;
import com.knife.blog.domain.BlogUser;
import com.knife.blog.logic.BlogCircleDirService;
import com.knife.blog.logic.BlogCircleDocService;
import com.knife.blog.logic.BlogCircleMemberService;
import com.knife.blog.logic.BlogCircleService;
import com.knife.blog.logic.BlogDirService;
import com.knife.blog.logic.BlogMessageService;
import com.knife.blog.logic.BlogNewsDocService;
import com.knife.blog.logic.BlogReviewService;
import com.knife.blog.logic.BlogUserService;
import com.knife.blog.logic.PhotoService;
import com.knife.blog.logic.impl.BlogCircleDirServiceImpl;
import com.knife.blog.logic.impl.BlogCircleDocServiceImpl;
import com.knife.blog.logic.impl.BlogCircleMemberServiceImpl;
import com.knife.blog.logic.impl.BlogCircleServiceImpl;
import com.knife.blog.logic.impl.BlogCoreServiceImpl;
import com.knife.blog.logic.impl.BlogMessageServiceImpl;
import com.knife.blog.logic.impl.BlogPhotoDirServiceImpl;
import com.knife.blog.logic.impl.BlogResourceServiceImpl;
import com.knife.blog.logic.impl.BlogReviewServiceImpl;
import com.knife.blog.logic.impl.BlogUserServiceImpl;
import com.knife.blog.logic.impl.FriendLinkServiceImpl;
import com.knife.blog.logic.impl.PhotoServiceImpl;
import com.knife.blog.util.BlogCommUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
import org.apache.velocity.io.VelocityWriter;

public class HTMLGenerater {
	private String baseDir;
	private String templateDir;
	private BlogUser bloguser;
	private static String encoding = "utf-8";
	private static final Logger logger = Logger
			.getLogger(RequestProcessor.class.getName());
	private static BlogUserService userService = BlogUserServiceImpl
			.getInstance();
	private static BlogDirService blogDirService = BlogCoreServiceImpl
			.getInstance();
	private static BlogNewsDocService blogDocService = BlogCoreServiceImpl
			.getInstance();
	private static PhotoService photoService = PhotoServiceImpl.getInstance();
	private static BlogReviewService reviewService = BlogReviewServiceImpl
			.getInstance();
	private static BlogMessageService messageService = BlogMessageServiceImpl
			.getInstance();
	private static BlogCircleDirService circleDirService = BlogCircleDirServiceImpl
			.getInstance();
	private static BlogCircleService circleService = BlogCircleServiceImpl
			.getInstance();
	private static BlogCircleDocService circleDocService = BlogCircleDocServiceImpl
			.getInstance();
	private static BlogCircleMemberService circleMemberService = BlogCircleMemberServiceImpl
			.getInstance();

	public HTMLGenerater() {
		this.baseDir = getBasePath();
		this.templateDir = getTemplatePath();
	}

	private String getClassPath() {
		String path = super.getClass().getClassLoader().getResource("").getPath();
		return path;
	}

	public String getTemplatePath() {
		String path = getClassPath().substring(0,getClassPath().indexOf("/classes/"))
				+ "/templates";
		if (path.indexOf("/") >= 0) {
			path = path.replace('/', File.separatorChar);
		}
		// System.out.println("模板路径是:"+path);
		return path;
	}

	public String getBasePath() {
		String path = getClassPath().substring(0,getClassPath().indexOf("/WEB-INF/classes/"));
		if (path.indexOf("/") >= 0) {
			path = path.replace('/', File.separatorChar);
		}
		// System.out.println("系统路径是:"+path);
		return path;
	}

	public boolean saveToHTML() {
		Context context = null;
		Template template = null;
		context = new VelocityContext();
		// List newsList = blogDocService.getTopBlogNewsDoc("displaytime desc",
		// 0, 10);
		List newsList = blogDocService
				.getTopBlogNewsDocBySql(
						"inputuser in(select username from bloginfo where (isNew is null or isNew=0) and (isHot is null or isHot=0)) order by displaytime desc",
						10);
		List hotReviewList = blogDocService.getTopBlogNewsDoc(null, null, null,
				null, "replyNum desc", 0, 20);
		List hotReadList = blogDocService.getTopBlogNewsDoc(null, null, null,
				null, "readTimes desc", 0, 20);
		List frindLinkList = FriendLinkServiceImpl.getInstance()
				.getTopFriendLink("admin", 15);

		List FamousBlogList = userService.getTopEliteBlogInfo("inputtime desc",
				1, 30);
		List NewBlogList = userService.getTopNewBlogInfo("inputtime desc", 1,
				10);
		List<BlogNewsDoc> NewBlogDocs = new ArrayList<BlogNewsDoc>();
		List<BlogNewsDoc> tmpList = new ArrayList<BlogNewsDoc>();
		BlogNewsDoc adoc = new BlogNewsDoc();
		if (NewBlogList != null) {
			for (int i = 0; i < NewBlogList.size(); i++) {
				BlogInfo ablog = (BlogInfo) NewBlogList.get(i);
				tmpList = blogDocService.getTopBlogNewsDoc(ablog.getUsername(),
						null, null, null, "displaytime desc", 0, 1);
				if (tmpList != null) {
					adoc = (BlogNewsDoc) tmpList.get(0);
				} else {
					adoc = new BlogNewsDoc();
					adoc.setTitle("暂无内容");
					adoc.setUrl("#");
				}
				NewBlogDocs.add(adoc);
			}
		}
		List HotBlogList = userService.getTopHotBlogInfo("inputtime desc", 1,
				10);
		context.put("list", newsList);
		context.put("hotReadList", hotReadList);
		context.put("hotReviewList", hotReviewList);
		context.put("FamousBlogList", FamousBlogList);
		context.put("NewBlogList", NewBlogList);
		context.put("NewBlogDocs", NewBlogDocs);
		context.put("HotBlogList", HotBlogList);
		context.put("frindLinkList", frindLinkList);

		addCommonContext(context);
		CommTool.createUtilContext(context);
		String fileName = "/index.htm";
		File file = new File(Config.getWwwpath() + fileName);
		if (!(file.getParentFile().exists())) {
			file.getParentFile().mkdirs();
		}
		String templateName = File.separator + "index.htm";
		template = VelocityFactory.getTemplate(templateName, "utf-8");
		mergeTemplate(template, context, file);
		return true;
	}

	public boolean saveToHtml(IPageList pList, String templateName,
			String filePath, BlogInfo blog) {
		Context context = null;
		Template template = null;
		context = new VelocityContext();
		context.put("blog", blog);
		bloguser=userService.getBlogUser(blog.getUsername());
		context.put("bloguser", bloguser);
		if (pList.getResult() == null) {
			context.put("list", null);
			String path = filePath;
			File file = new File(path);
			if (!(file.getParentFile().exists())) {
				file.getParentFile().mkdirs();
			}
			template = VelocityFactory.getTemplate(templateName, "utf-8");
			mergeTemplate(template, context, file);
			return true;
		}
		List list = pList.getResult();
		int resultNum = list.size();
		int pageSize = blog.getFirtpagenum().intValue();
		if (pageSize < 0)
			pageSize = 10;

		int pages = (resultNum % pageSize == 0) ? resultNum / pageSize
				: resultNum / pageSize + 1;
		for (int i = 0; i < pages; ++i) {
			String path;
			int page = i + 1;
			int begin = i * pageSize;
			int end = (i + 1) * pageSize;
			if (end > resultNum)
				end = resultNum;

			List pageList = list.subList(begin, end);
			context.put("list", pageList);
			context.put("pages", Integer.valueOf(pages));
			context.put("pageSize", Integer.valueOf(pageSize));
			context.put("rows", new Integer(pList.getRowCount()));
			context.put("page", Integer.valueOf(page));
			String fileName = filePath
					.substring(filePath.lastIndexOf(File.separator) + 1,
							filePath.length()).split("\\.")[0];

			context.put("gotoPageHTML",
					BlogCommUtil.showStaticPageHtml(fileName, page, pages));
			addCommonContext(context);

			int index = i + 1;
			if (index == 1) {
				path = filePath;
			} else {
				String newFileName = fileName + index;
				path = filePath.replace(fileName, newFileName);
			}

			File file = new File(path);
			if (!(file.getParentFile().exists()))
				file.getParentFile().mkdirs();

			template = VelocityFactory.getTemplate(templateName, "utf-8");
			mergeTemplate(template, context, file);
		}
		return true;
	}

	public void addCommonContext(Context context) {
		context.put("dirService", BlogCoreServiceImpl.getInstance());
		context.put("cocService", BlogCoreServiceImpl.getInstance());
		context.put("photoService", PhotoServiceImpl.getInstance());
		context.put("reviewService", BlogReviewServiceImpl.getInstance());
		context.put("messageService", BlogMessageServiceImpl.getInstance());
		context.put("userService", BlogUserServiceImpl.getInstance());
		context.put("linkService", FriendLinkServiceImpl.getInstance());
		context.put("resourceService",BlogResourceServiceImpl.getInstance());
		context.put("CommUtil", CommUtil.getInstance());
		context.put("HtmlUtil", HtmlUtil.getInstance());
		context.put("Config", Config.getInstance());
	}

	public String mergeFile(String mainFile, String contentFile,
			String[] navigatFile) {
		String main = file2String(new String[] { mainFile });
		String content = file2String(new String[] { contentFile });
		String navigate = file2String(navigatFile);
		main = main.replace("${content}", content);
		main = main.replace("${navigate}", navigate);
		return main;
	}

	public String file2String(String[] filename) {
		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		String[] arrayOfString = filename;
		int i = 0;
		for (int j = arrayOfString.length; i < j;) {
			String str = arrayOfString[i];
			try {
				reader = new BufferedReader(new FileReader(str));
				loadString(buffer, reader);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				if (reader != null)
					try {
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
			}
			++i;
		}

		return buffer.toString();
	}

	protected void loadString(StringBuffer buffer, BufferedReader br) {
		try {
			String str;
			while ((str = br.readLine()) != null)
				buffer.append(str + "\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected static void mergeTemplate(Template template, Context context,
			File file) {
		Writer writer = null;
		VelocityWriter vw = null;
		try {
			writer = new OutputStreamWriter(new FileOutputStream(file),
					template.getEncoding());
			vw = new VelocityWriter(writer, 4096, true);
			template.merge(context, vw);
		} catch (Exception e) {
			logger.error("合成错误：" + e);
			e.printStackTrace();
		} finally {
			if (vw != null)
				try {
					vw.flush();
					vw.close();
					writer.close();
				} catch (Exception e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				}
		}
	}

	/**
	 * 生成文章首页
	 * 
	 * @param blog
	 * @return
	 * @throws Exception
	 */
	public boolean saveIndexArticleToHTML() throws Exception {
		Context context = null;
		Template template = null;
		context = new VelocityContext();

		context.put("dirList", BlogCircleDirServiceImpl.getInstance());
		context.put("list", BlogCircleServiceImpl.getInstance());
		addCommonContext(context);
		CommTool.createUtilContext(context);
		String fileName = "article.htm";
		File file = new File(Config.getWwwpath() + "/" + fileName);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		String templateName = "/article.htm";
		template = VelocityFactory.getTemplate(templateName, "utf-8");
		mergeTemplate(template, context, file);
		return true;
	}

	/**
	 * 生成网站相册首页
	 * 
	 * @param blog
	 * @return
	 * @throws Exception
	 */
	public boolean saveIndexPhotoToHTML() throws Exception {
		Context context = null;
		Template template = null;
		context = new VelocityContext();

		context.put("dirList", BlogPhotoDirServiceImpl.getInstance());
		context.put("list", BlogPhotoDirServiceImpl.getInstance());
		addCommonContext(context);
		CommTool.createUtilContext(context);
		String fileName = "photo.htm";
		File file = new File(Config.getWwwpath() + "/" + fileName);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		String templateName = "/photo.htm";
		template = VelocityFactory.getTemplate(templateName, "utf-8");
		mergeTemplate(template, context, file);
		return true;
	}

	/**
	 * 生成圈子首页
	 * 
	 * @param blog
	 * @return
	 * @throws Exception
	 */
	public boolean saveIndexCircleToHTML() throws Exception {
		Context context = null;
		Template template = null;
		context = new VelocityContext();

		context.put("dirList", BlogCircleDirServiceImpl.getInstance());
		context.put("list", BlogCircleServiceImpl.getInstance());
		addCommonContext(context);
		CommTool.createUtilContext(context);
		String fileName = "circle.htm";
		File file = new File(Config.getWwwpath() + "/" + fileName);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		String templateName = "/circle.htm";
		template = VelocityFactory.getTemplate(templateName, "utf-8");
		mergeTemplate(template, context, file);
		return true;
	}

	public static void saveLeftReviewAllToHTML(BlogInfo blog) {
	}
}